/**
 * @Author: zc
 * @Date: 2020-07-06 14:22:34
 * @LastEditors: zc
 * @LastEditTime: 2020-07-07 14:42:51
 */
class Storage {
  public storage: any;
  constructor(storage: any) {
    if (!storage) {
      console.log('该浏览器不支持localStorage');
      return;
    }
    this.storage = storage;
  }
  /**
   * @function 设置值
   * @param {string} key 必须参数，属性
   * @param {any} value 非必须参数，属性值
   */
  setItem(key: string, value: any) {
    if (!this.storage) return;
    let kType = this.getType(key);
    if (kType === 'string') {
      this.storage.setItem(key, this.filterValue(value));
    } else {
      console.log('key只能是字符串！');
    }
  }

  /**
   * @function 获取值
   * @param {string} key 必须参数，属性
   */
  getItem(key: string) {
    if (!this.storage) return;
    let res;
    let kType = this.getType(key);
    if (kType === 'string') {
      res = JSON.parse(this.storage.getItem(key));
    } else {
      console.log('key只能是字符串！');
    }
    return res;
  }

  /**
   * @function 移除值
   * @param {string} key 必须参数，属性
   */
  removeItem(key: string) {
    if (!this.storage) return;
    let kType = this.getType(key);
    if (kType === 'string') {
      this.storage.removeItem(key);
    } else {
      console.log('key只能是字符串！');
    }
  }

  /**
   * @function 移除所有
   */
  clear() {
    if (!this.storage) return;
    this.storage.clear();
  }

  /**
   * @function 判断类型
   * @param {any} para 必须参数，判断的值
   */
  getType(para: any) {
    let type = typeof para;
    if (type === 'number' && isNaN(para)) return 'NaN';
    if (type !== 'object') return type;
    return Object.prototype.toString
      .call(para)
      .replace(/[\\[\]]/g, '')
      .split(' ')[1]
      .toLowerCase();
  }

  /**
   * @function 过滤值
   * @param {any} val 必须参数，过滤的值
   */
  filterValue(val: any) {
    let vType = this.getType(val);
    let nullVal = ['null', 'undefined', 'NaN'];
    let stringVal = ['boolen', 'number', 'string'];
    if (nullVal.indexOf(vType) >= 0) return '';
    if (stringVal.indexOf(vType) >= 0) return val;
    return JSON.stringify(val);
  }
}

export const lStorage = new Storage(window.localStorage || localStorage);
